package util.concurrent;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:Lock锁的使用
 * @author: Lidong
 * @time: 2020/5/18 10:43
 **/
public class LockTest {

    private static final Logger logger = LoggerFactory.getLogger(LockTest.class);

    @Test
    public void test1() {
        Lock lock = new ReentrantLock();
        int i = 0;
        while (true) {
            try {
                lock.lock();
                i++;
                logger.info("当前 i :{}", i);
                if (i == 1000) {
                    break;
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                lock.unlock();
            }
        }
    }

    @Test
    public void test2() {
        Tickets tickets = new Tickets();
        new Thread(tickets, "1号窗口").start();
        new Thread(tickets, "2号窗口").start();
        new Thread(tickets, "3号窗口").start();
    }

    static class Tickets implements Runnable {

        private final Logger logger = LoggerFactory.getLogger(Tickets.class);
        private int tickets = 100;
        private final Lock lock = new ReentrantLock();

        @Override
        public void run() {
            while (true) {
                /*上Lock锁*/
                lock.lock();
                try {
                    Thread.sleep(4000);
                    if (tickets > 0) {
                        logger.info(Thread.currentThread().getName() + "======" + "完成售票，余票为" + --tickets);
                    }
                } catch (Exception e) {
                    logger.error("Error Occur:{}", e.getMessage(), e);
                } finally {
                    /*释放Lock锁避免发生死锁*/
                    lock.unlock();
                }
            }
        }
    }

}

